package com.shwread.httpsdk.http.base;

import android.content.Context;
import android.content.Intent;

import com.google.gson.Gson;
import com.shwread.android.ui.dialog.SingleSignOnDialog;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.util.Base64;
import com.shwread.httpsdk.util.NetUtil;
import com.shwread.httpsdk.util.Util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.net.URI;
import java.util.HashMap;
import java.util.Map.Entry;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.AppUtils;

public abstract class AbstractHttpPostDracom extends AbstractHttpBase {
    protected long timeStamp = System.currentTimeMillis();
    protected Gson gson = new Gson();
    private HttpClient httpClient;
    //private DefaultHttpClient httpClient;
    private HttpPost requestPost;
    private String action;
    private HttpResponse response;
    private SingleSignOnDialog dialog;
    private HashMap<String, String> parameter_map = new HashMap<>();

    public AbstractHttpPostDracom(Context context, String action, ActionListener actionListener) {
        super(context, action, actionListener);
        this.action = action;
        setParameter();
    }

    public abstract void getParameter(HashMap<String, String> parameter_map);

    public abstract void doResponseXml(String xml);

    private void setParameter() {
        //if (Util.isNotEmpty(Const.phone_number)) parameter_map.put("account", Const.phone_number);
        parameter_map.put("accountType", Const.ACCOUNTTYPE);
        parameter_map.put("clientType", Const.CLIENTTYPE);
    }

    protected String getUrl() {
        String result = "";
        getParameter(parameter_map);
        if (parameter_map != null && !parameter_map.isEmpty()) {
            result += "?";
            for (Entry<String, String> entry : parameter_map.entrySet()) {
                result += entry.getKey() + "=" + entry.getValue() + "&";
            }
            result = result.substring(0, result.length() - 1);
        }
        println("请求URL：" + Const.SERVER_URL + "/" + action + result);
        return Const.SERVER_URL + "/" + action + result;
    }

    protected String cid(String value) {
        if (Util.isNotEmpty(Const.login_key)) return Base64.base64Encode(value, Const.login_key, "UTF-8");
        return Base64.base64Encode(value, Const.SERVER_ENCRYPTKEY, "UTF-8");
    }

    @Override
    protected void doHttp() {
        try {
            httpClient = new DefaultHttpClient(params);
            requestPost = new HttpPost(URI.create(getUrl()));
            for (Entry<String, String> entry : getHeader().entrySet()) {
                println("key:" + entry.getKey() + " value:" + entry.getValue());
                requestPost.addHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(requestPost);
            for (Header header : response.getAllHeaders()) {
                println("[header]:" + header.getName() + " " + header.getValue());
            }
            int code = response.getStatusLine().getStatusCode();
            println("code:" + code);

            if (code == HttpStatus.SC_OK) {
                final String result = new String(EntityUtils.toByteArray(response.getEntity()), Const.charset);
                int resCode = new JSONObject(result).getInt("resultCode");
                //帐号在别处登录
                if (DefaultConsts.EXCEPTION_LOGIN_CODE == resCode) {
                    Intent intent = new Intent(DefaultConsts.EXCEPTION_LOGIN_STRING);
                    intent.putExtra("json", result);
                    intent.putExtra("packageName", AppUtils.getPackageName(context));
                    context.sendBroadcast(intent);
                    //必填参数为空
                } else if (DefaultConsts.PARAMS_EMPTY_CODE == resCode) {
                    Intent intent = new Intent(DefaultConsts.PARAMS_EMPTY_STRING);
                    intent.putExtra("packageName", AppUtils.getPackageName(context));
                    context.sendBroadcast(intent);
                } else {
                    doResponseXml(result);
                }
            } else {
                HTTPERROR(code, null);
            }
        } catch (Exception e) {
            HTTPERROR(NetUtil.NetError, e);
        } finally {
            DoDispose();
        }
    }

    private void DoDispose() {
        if (response != null) {
            response = null;
        }
        if (requestPost != null) {
            requestPost.abort();
        }
        if (httpClient != null) {
            //httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
        if (parameter_map != null) {
            parameter_map.clear();
            parameter_map = null;
        }
        if (header_map != null) {
            header_map.clear();
            header_map = null;
        }
        if (listener != null) {
            listener = null;
        }
        dispose();
        context = null;
    }
}
